/**
 * 设置全局的ajax调用拦截
 */
var ajax_num = 0;
jQuery.ajaxSetup({
    cache:false,
    beforeSend:function(jqXHR){
        jqXHR.setRequestHeader('HTTP_AJAX_POST_HEADER', 'ajax');
        $(".ajax_loading").css("display","block");
        ajax_num++;
    },
    complete:function(jqXHR, textStatus){
        ajax_num-=1;
        if(ajax_num === 0){
            $(".ajax_loading").css("display","none");
        }
        var statusCode = jqXHR.status;
        if(statusCode != 200){
            if(statusCode >= 500){
                //后台发生了错误
                var errorMsg = jqXHR.responseText;
                try{
                    var json = Http.parseJSON(errorMsg);
                    if(json && typeof json["message"]=== "string"){
                        errorMsg = json["message"];
                    }
                }catch(e){}
                alert(errorMsg);
            }else if(statusCode == 0){
                //网络不通
                alert("网络中断，请检查网络！");
            }else{
                alert("服务器端发生未知错误，请稍后再试！");
            }
        }
    }
});
/**
 * 定义Http
 */
var Http = {};
Http.parseJSON = function(strJson){
    try{
        return eval("("+strJson+")");
    }catch(e){
        alert("转换json时出错:"+e+","+strJson,true);
    }
};
/**
 * 在settings配置中增加beforeHandler事件，即处理okHandler事件之前所处理的，
 * 若beforeHandler返回false，则不再处理后续的自定义事件
 *
 * settings:
 * {
 *      action:提交的url地址
 *      params:可以是一个json表达式
 *      async:是否同步,默认为true,即异步
 *      okHandler:成功处理后的回调函数
 *      errHandler:服务器返回有错误时的处理函数
 *      dataType:text|json
 * }
 *
 * @param settings
 * @param opts
 */
Http.doPost = function(settings){
    var async = true;  //默认为异步
    if(typeof settings.async === "boolean"){
        async = settings.async;
    }
    var params = settings.params || {};
    var type = settings.dataType || "json";
    $.ajax({
        type:"POST",
        async:async,
        url:settings.action,
        data:params,
        dataType:"text",
        success: function(data, textStatus, jqXHR) {
            var header = jqXHR.getResponseHeader("nologin");
            if(header == "nologin"){
                //当前用户已退出或超时
                Http.onProcessNologin();
                return;
            }
            if(type == "json"){
                data = Http.parseJSON(data);
                if(data["hasErrors"]){
                    //服务器返回了错误
                    processError(data["message"]);
                    if(typeof settings.errHandler === "function"){
                        settings.errHandler(data);
                    }
                }else{
                    if(typeof settings.okHandler === "function"){
                        settings.okHandler(data);
                    }
                    var msg = "";
                    if(typeof data.message === "string" && data.message.length>0){
                        msg = data.message;
                        alert(msg);
                    }
                }
            }else{
                if(typeof settings.okHandler === "function"){
                    settings.okHandler(data);
                }
            }

        }
    });
};
Http.post = function(url,data,okHandler){
    Http.doPost({
        action:url,
        params:data,
        okHandler:okHandler
    });
};
Http.post1 = function(url,data,handler){
    $.ajax({
        type:"POST",
        url:url,
        data:data,
        dataType:"text",
        success: function(data, textStatus, jqXHR) {
            handler(data);
        }
    });
};
/**
 * 在settings配置中增加beforeHandler事件，即处理okHandler事件之前所处理的，
 * 若beforeHandler返回false，则不再处理后续的自定义事件
 * 同步请求时处理事件中的数据为字符串格式
 * @param settings
 * @param opts
 */
Http.doGet = function(url,data,okHandler,opts){
    opts = opts || {};
    var async = true;
    if(typeof opts.async === "boolean"){
        async = opts.async;
    }
    opts.dataType = opts.dataType || "json";
    $.ajax({
        type:"GET",
        url:url,
        async:async,
        data:data,
        dataType:"text",
        success:function(data, textStatus, jqXHR){
            var header = jqXHR.getResponseHeader("nologin");
            if(header == "nologin"){
                //当前用户已退出或超时
                Http.onProcessNologin();
            }else{
                if(typeof opts.beforeHandler === "function"){
                    var ret = opts.beforeHandler(data,textStatus, jqXHR);
                    if(typeof ret === "boolean" && !ret){
                        //前置处理事件返回了false，则不再处理后续事件了
                        return;
                    }
                }
                if(opts.dataType === "json"){
                    data = Http.parseJSON(data);
                    if(data.hasErrors){
                        processError(data.message);
                        if(typeof opts.errHandler == "function"){
                            opts.errHandler(data);
                        }
                    }else{
                        if(typeof okHandler === "function"){
                            okHandler(data);
                        }
                    }
                }else{
                    okHandler(data);
                }
            }
        }
    });
};
/**
 * 通过 HTTP GET 请求从服务器载入 文本 数据。
 * @param url
 * @param data
 */
Http.getStr = function(url,data,opts){
    opts = opts || {};
    var ret = "";
    showLoading(opts);
    $.ajax({
        async:false,
        type:"GET",
        url:url,
        data:data,
        dataType:"text",
        success:function(data, textStatus, jqXHR){
            var header = jqXHR.getResponseHeader("nologin");
            if(header == "nologin"){
                //当前用户已退出或超时
                Http.onProcessNologin();
            }else{
                ret = data;
            }
        }
    });
    return ret;
};
Http.doGetHtml = function(url,data,successedHandler){
    $.ajax({
        type:"GET",
        url:url,
        data:data,
        dataType:"text",
        success:function(data, textStatus, jqXHR){
            var header = jqXHR.getResponseHeader("nologin");
            if(header == "nologin"){
                //当前用户已退出或超时
                Http.onProcessNologin();
            }else{
                successedHandler(data);
            }
        }
    });
};
Http.onProcessNologin = function(){
    alert("您的登录已超时,请重新登录!");
    top.location.reload();
};
function showLoading(opts){
    opts.showed = typeof opts.showed == "undefined" ? true : opts.showed;
    opts.text = typeof opts.text == "undefined" ? "正在从服务器获取数据..." : opts.text;
    if(opts.showed && typeof top.loading === "function"){
        top.loading(opts.text);
    }
};
/**
 * 将url参数数据[json]增加到url尾部
 * @param url
 * @param data
 */
Http.getUrl = function(url,data){
    if(!data){
        return url;
    }
    var _url = url;
    var params = "";
    var i = 0;
    for(var key in data){
        if(i++>0){
            params+="&";
        }
        params += key + "=" + data[key];
    }
    if(params != ""){
        if(_url.indexOf("?")==-1){
            _url += "?" + params;
        }else{
            _url += "&" + params;
        }
    }
    return _url;
};
function hideLoading(opts){
    if(typeof top.hide1 === "function"
        && (!opts || typeof opts.showed === "undefined" || opts.showed)){
        //alert("hideLoadding");
        top.hide1();
    }
}

function processError(errMsg){
    if(!errMsg || errMsg.length==0){
        return;
    }
    var errorContainer = $("div.error");
    var items = [];
    if(errorContainer.length==0){
        //以弹窗口的形式显示错误
        if(typeof errMsg === "string"){
            items.push(errMsg);
        }else{
            $.each(errMsg, function(i,val) {
                if(typeof val === "string"){
                    items.push((i+1)+'.' + val + '\n');
                }else{
                    if(typeof val.key === "string" && val.key.length>0){
                        items.push((i+1)+'.' + val.key+" - "+val.msg + "\n");
                    }else{
                        items.push((i+1) + '.' +val.msg+'\n');
                    }
                }
            });
        }
        var errorMsg = items.join("");
        alert(errorMsg);
    }else{
        //直接在页面上显示错误信息
        //先清除上次的错误
        errorContainer.empty();
        var error = $("<ul/>");
        error.appendTo(errorContainer);
        if(typeof errMsg === "string"){
            items.push('<li>' + errMsg + '</li>');
        }else{
            $.each(errMsg, function(i,val) {
                if(typeof val === "string"){
                    items.push('<li>' + val + '</li>');
                }else{
                    if(typeof val.key === "string" && val.key.length>0){
                        items.push('<li>'+val.key+" - "+val.msg+'</li>');
                    }else{
                        items.push('<li>'+val.msg+'</li>');
                    }
                }
            });
        }
        error.html(items.join(""));
    }
}